package com.gxuwz.interceptor;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录验证的过滤器
 */


@WebFilter("/*")
public class LoginFilter implements Filter {

    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;

        //判断访问的资源路径是否和登陆注册相关
        String[] urls = {"/login.html","/register.html","/login/register","/images/","/css/","/js/","/loginHome","/login/checkCode","/login"};
        //获取当前访问的资源路径
        String url = req.getRequestURL().toString();
        //循环判断
        for ( String u : urls ) {
            if(url.contains(u)) {
                //放行
                chain.doFilter(request, response);
                return;
            }
        }
        //1.判断session中是否user
        HttpSession session = req.getSession();
        Object user = session.getAttribute("username");

        //2.判断user是否为null
        if(user != null){
            chain.doFilter(request, response);
        }else {
            //没有登录，存储提示信息，跳转到登陆界面
            RequestDispatcher dispatcher = req.getRequestDispatcher("/loginHome");
            dispatcher.forward(request, response);
        }
    }
}
